<!-- 登录页 -->
<template>
	<div class="login">
		<el-form ref="loginRef" :model="loginForm" :rules="loginRules" class="login-form">
			<div class="title"><img src="@/assets/images/sidbar_logo.png" alt="" /></div>
			<!-- 账号 -->
			<el-form-item prop="username" class="username">
				<el-input v-model.trim="loginForm.username" type="text" size="large" auto-complete="off" placeholder="请输入账号" ref="userRef" @input="inputChange">
					<template #prefix><svg-icon icon-class="user" class="el-input__icon input-icon" /></template>
				</el-input>
			</el-form-item>

			<!-- 密码 -->
			<el-form-item prop="password">
				<el-input v-model.trim="loginForm.password" type="password" size="large" auto-complete="off" placeholder="请输入密码" show-password @keyup.enter="handleLogin" ref="psdRef">
					<template #prefix><svg-icon icon-class="psd" class="el-input__icon input-icon psd" /></template>
				</el-input>
			</el-form-item>

			<div class="psd-container">
				<!-- 记住密码 -->
				<el-checkbox v-model="loginForm.rememberMe" class="rem-box">记住密码</el-checkbox>
				<div class="forgot-psd" @click="forgotPsd">忘记密码</div>
			</div>

			<!-- 登录按钮 -->
			<el-form-item>
				<el-button :loading="loading" size="large" type="primary" class="submit-btn w100" @click.prevent="handleLogin">
					<span v-if="!loading">登 录</span>
					<span v-else>登 录 中...</span>
				</el-button>
			</el-form-item>
		</el-form>
	</div>
	<!-- 备案号 -->
	<Icp />
</template>

<script setup>
import Icp from '@/components/Icp/index.vue'
import Cookies from 'js-cookie'
import { encrypt, decrypt } from '@/utils/jsencrypt'
import useUserStore from '@/store/modules/user'
import useSettingsStore from '@/store/modules/settings'
import { getPhoneNumberAPI } from '@/api/login'
const userStore = useUserStore()
const route = useRoute()
const router = useRouter()
const { proxy } = getCurrentInstance() // this
const updateUserName = localStorage.getItem('userName') // 强制修改密码页面跳转-回显用户名
// 登录参数
const loginForm = ref({
	username: updateUserName || '', // 用户名
	password: '', // 密码
	rememberMe: false // 记住密码
})
// 登录验证规则
const loginRules = {
	username: [
		{ required: true, trigger: 'blur', message: '请输入您的账号' }
		// { min: 2, max: 20, message: '账户长度必须介于6到20个字符之间', trigger: 'blur' }
	],
	password: [
		{ required: true, trigger: 'blur', message: '请输入您的密码' },
		// { min: 6, max: 20, message: '用户密码长度必须介于6到20个字符之间', trigger: 'blur' },
		{ pattern: /^[a-zA-Z0-9!@#$%^&*]+$/, message: '密码只能输入数字，字母，特殊符号', trigger: 'blur' }
	]
}

const loading = ref(false) // loading状态
const redirect = ref(undefined) // 重定向地址

// 监视当前路由是否有重定向地址
watch(
	route,
	(newRoute) => {
		redirect.value = newRoute.query && newRoute.query.redirect
	},
	{ immediate: true }
)

// 监听账号小写字母转大写
watch(
	() => loginForm.value.username,
	(newVal) => {
		loginForm.value.username = newVal.toUpperCase()
	}
)

// 登录操作
function handleLogin() {
	proxy.$refs.loginRef.validate((valid) => {
		if (valid) {
			loading.value = true
			// 勾选了需要记住密码设置在 cookie 中设置记住用户名和密码
			if (loginForm.value.rememberMe) {
				Cookies.set('username', loginForm.value.username, { expires: 30 })
				Cookies.set('password', encrypt(loginForm.value.password), {
					expires: 30
				})
				Cookies.set('rememberMe', loginForm.value.rememberMe, { expires: 30 })
			} else {
				// 否则移除
				Cookies.remove('username')
				Cookies.remove('password')
				Cookies.remove('rememberMe')
			}
			// 调用action的登录方法
			userStore
				.login(loginForm.value)
				.then(() => {
					const query = route.query
					const otherQueryParams = Object.keys(query).reduce((acc, cur) => {
						if (cur !== 'redirect') {
							acc[cur] = query[cur]
						}
						return acc
					}, {})
					router.push({ path: redirect.value || '/', query: otherQueryParams })
				})
				.catch(() => {
					loading.value = false
				})
		}
	})
}
// 忘记密码
const forgotPsd = () => {
	proxy.$refs.loginRef.validateField('username', async (valid) => {
		if (valid) {
			let res = await getPhoneNumberAPI({
				account: loginForm.value.username
			})
			router.push({
				path: '/forgot-password',
				state: {
					phoneNumber: res.data.phoneNumber,
					account: res.data.account
				}
			})
		}
	})
}

onMounted(() => {
	if (!loginForm.value.username) {
		proxy.$refs.userRef.focus()
	}
	if (loginForm.value.username && !loginForm.value.password) {
		proxy.$refs.psdRef.focus()
	}
})
// 清除强制修改密码跳转-存储的userName
onBeforeUnmount(() => {
	localStorage.removeItem('userName')
})

// 获取cookie, 记住密码时的操作
function getCookie() {
	const username = Cookies.get('username')
	const password = updateUserName ? undefined : Cookies.get('password')
	const rememberMe = Cookies.get('rememberMe')
	loginForm.value = {
		username: username === undefined ? loginForm.value.username : username,
		password: password === undefined ? loginForm.value.password : decrypt(password),
		rememberMe: rememberMe === undefined ? false : Boolean(rememberMe)
	}
}
getCookie()
// 如果用户清空了账号，自动清空密码
function inputChange(e) {
	if (e == '') {
		loginForm.value.password = ''
	}
}
</script>

<style lang="scss" scoped>
.login {
	display: flex;
	flex-direction: column;
	justify-content: center;
	align-items: center;
	height: 100%;
	background-image: url('https://glm-1324073348.cos.ap-nanjing.myqcloud.com/2024/10/18/fa076049315040fd86a62760486af3071729231799530.png');
	background-size: 100% 100%;
}
.login-form {
	border-radius: 6px;
	background: #ffffff;
	width: 400px;
	padding: 25px 25px 5px 25px;
	background-color: transparent;
	.psd-container {
		display: flex;
		align-items: center;
		margin-bottom: 14px;
		justify-content: space-between;
		.forgot-psd {
			font-size: 14px;
			color: #fff;
			cursor: pointer;
		}
	}
	.title {
		display: flex;
		justify-content: center;
		margin-bottom: 40px;
	}
	.el-input {
		height: 40px;
		background-color: transparent;
		input {
			height: 40px;
		}
	}
	.input-icon {
		height: 40px;
		width: 16px;
		margin-left: 0px;
		color: #fff;
	}
}
// 备案样式
.icp-container {
	position: absolute;
	bottom: 30px;
	width: 100%;
	text-align: center;
	color: #fff;
	font-size: 14px;
	.icp {
		img {
			width: 16px;
			height: 16px;
			margin-right: 4px;
			vertical-align: middle;
		}
		span {
			vertical-align: middle;
		}
	}
}
.rem-box {
	color: #fff;
}
// .rem-box:hover {
// 	color: #265bae;
// }
.username {
	margin-bottom: 28px;
}
// 输入框文字
:deep(.el-input__inner) {
	color: #fff !important;
}
// 输入框背景色
:deep(.el-input__wrapper) {
	background-color: rgb(255, 255, 255, 0.01);
}
// 输入框的placeholder
:deep(.el-input__inner::placeholder) {
	color: #fff;
}
// 密码眼睛
:deep(.el-input__password) {
	font-size: 20px;
	color: #fff;
}
// 禁止勾选记住密码后文字变成蓝色
:deep(.el-checkbox__input.is-checked + .el-checkbox__label) {
	color: #fff;
}
// input在浏览中自动填充后的默认样式 input:-internal-autofill-selected
::v-deep(input:-webkit-autofill) {
	-webkit-box-shadow: 0 0 0 0px transparent inset !important;
}
::v-deep(input:-internal-autofill-previewed, input:-internal-autofill-selected) {
	-webkit-text-fill-color: #ffffff !important;
	transition: background-color 5000s ease-in-out 0s !important;
}
::v-deep(input:-internal-autofill-selected) {
	transition: background-color 5000s ease-in-out 0s !important;
	background-color: transparent !important;
	-webkit-text-fill-color: #fff !important;
}
</style>
